<template>
	<div class="month-select">
		<div class="header cc-flex flex-h-between flex-v-center">
			<div class="left" @click="getLeftMonth()">{{ '<<' }}</div>
			<div class="title">日期选择</div>
			<div class="right" @click="getRightMonth">{{ canRight ? '>>' : ' ' }}</div>
		</div>
		<div class="content cc-flex flex-wrap">
			<div
				@click="dateSelect(date, `${date.year}${date.month}`)"
				:class="{ active: selectString == `${date.year}${date.month}` }"
				class="item cc-flex flex-v flex-center"
				v-for="(date, index) of monthes.list"
				:key="index"
			>
				<div>{{ date.year }}年</div>
				<div>{{ date.month }}月</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, reactive } from 'vue'
import { UtilsService } from '@/modules/common'
const selectString = ref('')
const monthes: { list: Array<{ year: number; month: number }> } = reactive({ list: [] })
const current = new Date()
monthes.list = UtilsService.getMonthes(-15, new Date().getFullYear(), current.getMonth() + 1)
onMounted(() => {
	const dateTemp = monthes.list[monthes.list.length - 1]
	const sString = `${dateTemp.year}${dateTemp.month}`
	dateSelect(monthes.list[monthes.list.length - 1], sString)
})
const canRight = computed(() => {
	const lastDate = monthes.list[monthes.list.length - 1]
	return lastDate.year * 100 + lastDate.month < current.getFullYear() * 100 + current.getMonth() + 1
})
const emit = defineEmits<{
	(e: 'onDateChange', date: any): void
}>()
function getLeftMonth() {
	const last = monthes.list[0]
	monthes.list = UtilsService.getMonthes(-15, last.year, last.month)
}
function getRightMonth() {
	const last = monthes.list[monthes.list.length - 1]
	monthes.list = UtilsService.getMonthes(15, last.year, last.month)
}
function dateSelect(date: any, sString: string) {
	selectString.value = sString
	emit('onDateChange', date)
}
</script>

<style scoped lang="scss">
.month-select {
	width: 400px;
	border: 1px solid #eee;
	padding: 10px;
	.header {
		.left,
		.right {
			font-size: 18px;
			cursor: pointer;
		}
	}
	.content {
		margin-top: 10px;
		.item {
			width: 80px;
			box-sizing: border-box;
			border: 1px solid #eee;
			padding: 5px;
			cursor: pointer;
			&:hover {
				color: var(--el-color-primary);
			}
		}
		.active {
			background-color: var(--el-color-primary);
			color: #fff;
			box-shadow: 0px 0px 10px var(--el-color-primary);
			border-width: 0px;
			&:hover {
				color: white;
			}
		}
	}
}
</style>
